package com.dy.controller;

import com.alibaba.fastjson.JSON;
import com.dy.domain.Living;
import com.dy.domain.User;
import com.dy.service.LivingService;
import com.dy.service.UserService;
import com.kaoshi.common.config.Result;
import live.LiveChannel;
import lombok.extern.slf4j.Slf4j;
import net.polyv.common.v1.exception.PloyvSdkException;
import net.polyv.live.v1.service.channel.impl.LiveChannelOperateServiceImpl;
import net.polyv.live.v2.entity.channel.operate.LiveChannelV2Request;
import net.polyv.live.v2.entity.channel.operate.LiveChannelV2Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/live")
@Slf4j
public class LiveController {
    private final StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserService userService;
    @Autowired
    private LivingService livingService;

    public LiveController(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @RequestMapping("/kaibo/{uid}")
    public Result<LiveChannel> kaibo(@PathVariable Integer uid){
        LiveChannel liveChannel = new LiveChannel();
        User byId = userService.findById(uid);
        try {
            //封装API请求对象
            LiveChannelV2Request liveChannelRequest = new LiveChannelV2Request();
            liveChannelRequest.setNewScene("alone")
                    .setTemplate("portrait_alone")
                    .setName(byId.getName()+"的直播") //设置频道主题信息
                    .setChannelPasswd("666888");   //设置频道密码
            //调用SDK请求保利威服务器
            LiveChannelV2Response liveChannelResponse = new LiveChannelOperateServiceImpl().createChannelV2(liveChannelRequest);
            //Assert.assertNotNull(liveChannelResponse);
            //正常返回做B端正常的业务逻辑
            if (liveChannelResponse != null){
                //to do something
                log.debug("频道创建成功{}", JSON.toJSONString(liveChannelResponse));
                log.debug("网页开播地址：https://live.polyv.net/web-start/login?channelId={},登录密码： {}",liveChannelResponse.getChannelId(),liveChannelRequest.getChannelPasswd());
                liveChannel.setChannelId(liveChannelResponse.getChannelId());
                liveChannel.setChannelPasswd(liveChannelResponse.getChannelPasswd());
                liveChannel.setUserId(liveChannelResponse.getUserId());
                liveChannel.setLiveUrl("https://live.polyv.net/web-start/login?channelId="+liveChannelResponse.getChannelId());
                log.debug("网页观看地址：https://live.polyv.cn/watch/{} ",liveChannelResponse.getChannelId());
            }

        } catch (PloyvSdkException e) {
            //参数校验不合格 或者 请求服务器端500错误，错误信息见PloyvSdkException.getMessage()
            log.error(e.getMessage(), e);
            // 异常返回做B端异常的业务逻辑，记录log 或者 上报到ETL 或者回滚事务
        } catch (Exception e) {
            log.error("SDK调用异常", e);
        }
        Living living = new Living();
        living.setZbname(byId.getName());
        living.setUid(uid);
        living.setUuid(liveChannel.getUserId());
        living.setLid(Integer.parseInt(liveChannel.getChannelId()));
        livingService.add(living);
        return Result.ok(liveChannel);
    }

    private Jedis jedis;
    @PostConstruct
    public void init() {
        this.jedis = new Jedis("localhost", 6379);
    }


    @RequestMapping("/hb/{num}/{price}/{uid}")
    public Result kaibo2(@PathVariable Integer num,@PathVariable Double price,@PathVariable Integer uid){
        User user= userService.findById(uid);
        if (user==null){
            return Result.fail("用户未登录");
        }else if (user.getDoucoin()<price){
            return Result.fail("抖币余额不足");
        }
        Random random=new Random();
        int a=100;
        Double[] arr=new Double[num];
        int num2=num;
        int i=0;
        //随机数
        for(;;){
            double min=0.01;
            double max=price;
            double c=min+(max-min)*random.nextDouble();
            if (c>price/2){
                continue;
            }
            String str=String.format("%.2f",c);
            c=Double.parseDouble(str);
//			System.out.println(c);
            if (price-c>=num2*0.01&&c<price&&i<num-1&&c<=price/2){
                num2--;
                arr[i++]=c;
                price-=c;
                //将数据存入redis消息队列
                jedis.lpush("hb"+uid,""+c);
            }else if (i==num-1){
                String str1=String.format("%.2f",price);
                price=Double.parseDouble(str1);
                arr[i]=price;
                jedis.lpush("hb"+uid,""+price);
                break;
            }
        }
        Double ss=0.0;
        for (Double v : arr) {
            System.out.println(v);
            ss+=v;
        }
        String str2=String.format("%.2f",ss);
        ss=Double.parseDouble(str2);
        System.out.println(ss);
        return Result.ok(arr);
    }
    @RequestMapping("/get/{uid}/{uuid}")
    public Result get(@PathVariable Integer uid,@PathVariable Integer uuid){
        String lockKey=""+uid;
        User byId = userService.findById(uuid);
        try {
            Boolean result=stringRedisTemplate.opsForValue().setIfAbsent(lockKey, ""+uid,10, TimeUnit.SECONDS);
            if (!result) {
                return Result.fail("手慢了");
            };
            //查看消息队列还有几位
            Long size=jedis.llen("hb"+uid);
            System.out.println("剩余"+size+"位");
            if (size==0){
                return Result.fail("没有红包了");
            }
            List<String> message=jedis.brpop(0, "hb"+uid);
            //将string转为double
            Double d=Double.parseDouble(message.get(1));
            byId.setDoucoin(byId.getDoucoin()+d);
            userService.updateById(byId);
            return Result.ok(d);
        }finally {
            stringRedisTemplate.delete(lockKey);
        }
    }

}
